<?php

namespace Iwester\Http\Controllers\Admin\Seo;

use Iwester\Http\Controllers\Admin\BaseController;
use Iwester\Console\Commands\SiteMap;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Iwester\Services\SitemapService;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;

class AdminSeoSitemapController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * sitemap
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function sitemap()
    {
        $sitemap = '';
        if(file_exists(public_path('sitemap.xml'))) {
            $sitemap = file_get_contents(public_path('sitemap.xml'));
            $sitemap  = str_replace("\n","<br />",$sitemap);
        }
        return view('iwester::admin.seo.sitemap.sitemap', ['sitemap' => $sitemap]);
    }

    /**
     * 更新sitemap
     * @return array
     */
    public function update(){
        try{
            $siteMapBack = $this->siteMapCreate();
            if($siteMapBack){
                return ['code'=> 200, 'message'=> 'sitemap更新成功！'];
            }else{
                return ['code'=> 201, 'message'=> 'sitemap更新失败！'];
            }
        }catch (\Exception $e){
            return ['code'=> 201, 'message'=> 'sitemap更新失败！'];
        }
    }

    /**
     * @return bool
     */
    public function siteMapCreate()
    {
        try {
            \File::exists(public_path('sitemap')) or \File::makeDirectory(public_path('sitemap'));
            Log::info('[' . date('Y-m-d H:i:s', time()) . ']开始执行sitemap生成脚本');
            $sitemapService = new SitemapService($this->siteConfig);
            $sitemapService->buildIndex();
            Log::info('[' . date('Y-m-d H:i:s', time()) . ']生成sitemap成功!');
            $api = $this->siteConfig->sitemap_api;
            $urls = [
                $this->siteConfig->site_url.'/sitemap.xml'
            ];
            $ch = curl_init();
            $options =  array(
                CURLOPT_URL => $api,
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => implode("\n", $urls),
                CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
            );
            curl_setopt_array($ch, $options);
            $result = curl_exec($ch);
            Log::info('[' . date('Y-m-d H:i:s', time()) . ']sitemap推送!');
            Log::info($result);
            return true;
        } catch (\Exception $exception) {
            $this->error('生成sitemap失败：' . $exception->getMessage());
            return false;
        }
    }
}
